<template>
  <div class="app-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="我的应用" @click-left="onBack"></van-nav-bar>

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
  import { ref } from 'vue'
  import { login } from '@/api/user'
  import { showToast } from 'vant'
  import { useStore } from 'vuex'
  import { useRouter } from 'vue-router'
  import { setToastDefaultOptions, resetToastDefaultOptions } from 'vant'
  export default {
    setup() {
      const username = ref('')
      const password = ref('')

      const store = useStore()
      const router = useRouter()

      const onBack = () => history.back()

      setToastDefaultOptions({ duration: 1000 })

      const onSubmit = (values) => {
        login(values).then((res) => {
          if (res.data.loginStatus) {
            store.commit('setUser', res.data)
            showToast({
              message: '登录成功',
              type: 'success',
              className: 'toast',
              overlay: true,
            })
            router.push({ path: '/home' })
          } else {
            showToast({
              message: '账号或密码不正确',
              type: 'fail',
              className: 'toast',
            })
          }
        })
      }

      return {
        username,
        password,
        onSubmit,
        onBack,
      }
    },
  }
</script>

<style scoped>
  .container {
    width: 100%;
    height: 100%;
    background-image: url('../../assets/image/back-ground.png');
    background-size: 100%;
  }
</style>
